package server;

import javax.jms.ObjectMessage;
import javax.jms.Queue;

import job.Job;

public class JMSServer {
	private static final int MAX_JOBS = 10;
	private static final int MAX_WAIT = 5;
	
	// 0 - randomized
	// 1 - topic based
	private static final int RANDOMIZED = 0;
	private static final int TOPIC_BASED = 1;
	private static final int DEFAULT = TOPIC_BASED;
	
	
	public static void main(String[] args) {
		int type = DEFAULT;
		int jobs = MAX_JOBS;
		
		try {
			type = (args.length>=1)? Integer.parseInt(args[0]) : DEFAULT;
			jobs = (args.length>=2)? Integer.parseInt(args[0]) : MAX_JOBS;
		} catch (Exception e) {
			System.out.println("ERROR: incorrect input");
		}
		
		if(type!=RANDOMIZED && type!=TOPIC_BASED) {
			type = DEFAULT;
		}
		
		try {
			if(type==RANDOMIZED) {
				
				ObjectMessage message;
				int timeToSleep;
				int wait = MAX_WAIT;
				try {
					wait = (args.length==3)? Integer.parseInt(args[1]) : MAX_WAIT;
				} catch (Exception e) {
					System.out.println("ERROR: incorrect input");
				}
				
				RandomizedServer server = new RandomizedServer(jobs);
				
				server.start();
				
				System.out.println("Randomized server ready and waiting (" + server.getId() + ") ...\n");
				
				while(true) {
					if(Math.random()<server.getProb()) {
                        message = (ObjectMessage) server.getQueueReceiver().receive();
                        Queue replyTo = (Queue) message.getJMSReplyTo();
                        Job job = (Job) message.getObject();

                        server.addJob(job.getName());
                        
                        new RandomizedThread(server, job, replyTo).start();
					} else {
						timeToSleep = (int)((1-server.getProb())*wait);
						if(timeToSleep>1) {
							//System.out.println(">> i'm too load - sleep "+timeToSleep+" seconds");
							Thread.sleep(timeToSleep*1000);
						}
					}
				}
			} else if(type==TOPIC_BASED) {
				ObjectMessage message;
				
				TopicBasedServer server = new TopicBasedServer(jobs);
				
				server.start();
			    
			    System.out.println("Topic Based server ready and waiting (" + server.getId() + ") ...\n");
				
				while(true) {
					
					message = (ObjectMessage) server.getQueueReceiver().receive();

                    Queue replyTo = (Queue) message.getJMSReplyTo();
                    Job job = (Job) message.getObject();

                    server.addJob(job.getName());
                    server.shout();
                    
                    server.verify();	             

					new TopicBasedThread(server, job, replyTo).start();
					
				}
			} else {
				System.out.println("Unrecognized option: shutting down ...\n");
			}
			
			
		} catch(Exception e) { 
			e.printStackTrace();
		}
		
	}
}

